<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list">
              <el-table-column label="序号" type="index" width="120" />
              <el-table-column label="角色名称" prop="name" width="240" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="hAssgin(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page="pageMessage.page"
                :page-sizes="[1, 2, 5, 7, 10, 20]"
                :page-size="pageMessage.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增角色弹层的显示与隐藏 -->
      <el-dialog title="新增角色" :visible.sync="showDialog" @close="detail">
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="showDialog = false">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>

      <!-- 给角色分配权限 -->
      <el-dialog v-if="roleShowDialog" title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)" :visible.sync="roleShowDialog">
        <assignPermission :id="curId" @close="roleShowDialog=false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
// 导入
import { getRolesList, addRolesList, updateRolesList, delRolesList } from '@/api/settings'
import assignPermission from './assignPermission.vue'

export default {
  components: {
    assignPermission
  },
  data() {
    return {
      // 当前角色id
      curId: '',
      // 控制分配权限弹层显示与隐藏
      roleShowDialog: false,
      // 控制是编辑还是新增
      isEdit: false,
      // 获取的数据对象
      roleForm: {
        name: '',
        description: ''
      },
      // 校验规则
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 控制对话框的显示与隐藏
      showDialog: false,
      pageMessage: {
        page: 1, // 页码值
        pagesize: 2 // 每页的条数
      },
      // 存储每页的角色列表数据
      list: [],
      total: 0 // 角色的总数量
    }
  },
  created() {
    this.loadRolesList()
  },
  methods: {
    // 分配角色获取id和打开弹层
    hAssgin(id) {
      this.curId = id
      this.roleShowDialog = true
    },
    // 重置
    detail() {
      this.$refs.roleForm.resetFields()
      this.roleForm = {
        name: '',
        description: ''
      }
    },
    // 删除角色
    hDel(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 确认删除该角色
        await delRolesList(id)
        if (this.list.length === 1) {
          this.pageMessage.page--
          if (this.pageMessage.page <= 0) {
            this.pageMessage.page = 1
          }
        }
        // 重新渲染
        this.loadRolesList()
        // 提示消息
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 新增弹层
    hAdd() {
      this.isEdit = false
      this.showDialog = true
    },
    // 编辑弹层
    hEdit(data) {
      this.isEdit = true
      // 把数据存入到data中的form表单中
      this.roleForm = { ...data }
      this.showDialog = true
    },
    // 新增角色
    async doAdd() {
      try {
        const res = await addRolesList(this.roleForm)
        console.log('addRolesList', res)
        // 获取到添加后最大页码值, 使添加后直接显示到最后一页上
        // 计算出最大的页码值: 公式 Math.ceil(this.total / this.pageMessage.pagesize)
        // 因为此时获取total还没有渲染
        this.total++
        const maxPage = Math.ceil(this.total / this.pageMessage.pagesize)
        this.pageMessage.page = maxPage
        // 重新渲染
        this.loadRolesList()
        // 关闭弹层
        this.showDialog = false
      } catch (error) {
        console.log('error', error)
      }
    },
    // 编辑保存角色
    async doEdit() {
      try {
        await updateRolesList(this.roleForm)
        // 提示成功
        this.$message.success('更新角色详情成功')
        // 重新渲染
        this.loadRolesList()
        // 关闭弹层
        this.showDialog = false
      } catch (error) {
        console.log('error', error)
      }
    },
    // 新增角色的兜底校验
    hSubmit() {
      this.$refs.roleForm.validate(valid => {
        if (!valid) return // 校验失败
        // 校验成功, 发送请求
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      // 每修改每页显示条数时, 应该先设置页码值为1
      this.pageMessage.page = 1
      // 修改pageMessage里的pagesize的值
      this.pageMessage.pagesize = val
      // 发送请求, 重新获取数据, 渲染到页面
      this.loadRolesList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      // 修改pageMessage里的page值
      this.pageMessage.page = val
      // 发送请求, 重新获取数据, 渲染到页面
      this.loadRolesList()
    },
    // 获取角色列表
    async loadRolesList() {
      try {
        const res = await getRolesList(this.pageMessage)
        console.log('getRolesList', res)
        // 把获取的数据存储到data函数中去
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log('error', error)
      }
    }
  }
}
</script>
